from django.shortcuts import render
from django.http import HttpResponse,JsonResponse

from .cates import get_cates_all
from .user import uploads_pic

from ..models import Cates, Goods


# Create your views here.

# 商品添加 表单
def goods_add(request):
    # 获取当前所有的分类数据
    data = get_cates_all()
    # 分配数据
    context = {'catelist': data}

    # 显示一个添加的表单
    return render(request, 'myadmin/goods/add.html', context)


def goods_insert(request):
    try:

        # 接收表单数据
        data = request.POST.dict()
        print(data)
        data.pop('csrfmiddlewaretoken')

        # 处理 分类对象
        data['cateid'] = Cates.objects.get(id=data['cateid'])
        # 判断是否有图片上传
        myfile = request.FILES.get('pic', None)
        if not myfile:
            return HttpResponse('<script>alert("必须上传商品图片");history.back(-1);</script>')
        # 处理  上传的文件
        data['pic_url'] = uploads_pic(myfile)

        # 执行添加
        ob = Goods(**data)
        ob.save()

        return HttpResponse('<script>alert("商品添加成功");location.href="/myadmin/goods/index/";</script>')
    except:
        pass

    return HttpResponse('<script>alert("商品添加失败");history.back(-1);";</script>')


def goods_index(request):
    # 获取所有的商品对象
    # 获取所有用户数据
    data = Goods.objects.all().exclude(status=2)

    # 获取搜索条件
    types = request.GET.get('types', None)
    keywords = request.GET.get('keywords', None)
    # 判断是否搜索
    if types == 'all':
        from django.db.models import Q
        data = data.filter(Q(id__contains=keywords) | Q(goodsname__contains=keywords) | Q(title__contains=keywords))
    elif types:
        search = {types + '__contains': keywords}
        data = data.filter(**search)

    # 导入分页类
    from django.core.paginator import Paginator
    # 实例化分页类
    p = Paginator(data, 10)
    # 获取当前的页码数
    pageindex = request.GET.get('page', 1)
    # 获取当前页的数据
    userlist = p.page(pageindex)
    # 获取所有的页码
    # pages = p.page_range
    # pages = p.num_pages

    # 分配数据
    context = {'goodslist': data}

    # 加载模板
    return render(request, 'myadmin/goods/index.html', context)
#更改数据
def goodsEdit(request):
    # 获取当前所有的分类数据
    data = get_cates_all()
    # 分配数据
    uid = request.GET.get('uid')
    ob = Goods.objects.get(id=uid)
    context ={'goods':ob,'catelist': data}
    return render(request, "myadmin/goods/edit.html",context)


#更改单条状态
def goodsSetStatus(request):
    # 通过uid获取当前会员对象
    ob = Goods.objects.get(id=request.GET.get('uid'))
    ob.status = request.GET.get('status')
    ob.save()
    return JsonResponse({'msg': '状态更新成功', 'code': 0})

#更改多条数据状态
def goodsetManyStatus(request):
    # 通过uid获取当前会员对象
    print(request.GET)
    ids=request.GET.getlist('ids[]')
    status=request.GET.get('status')
    for i in ids:
        ob = Goods.objects.get(id=i)
        ob.status = status
        ob.save()
    return JsonResponse({'msg': '状态更新成功', 'code': 0})




# 头像上传的处理代码
def uploads_pic(myfile):
    try:
        import time
        filename = str(time.time())+"."+myfile.name.split('.').pop()
        destination = open("./static/uploads/"+filename,"wb+")
        for chunk in myfile.chunks():# 分块写入文件
            destination.write(chunk)
        destination.close()
        return '/static/uploads/'+filename
    except:
        return False



def goodsDel(request):
    ob = Goods.objects.get(id=request.GET.get('uid'))
    # ob.delete()
    ob.status = 2
    ob.save()
    return HttpResponse('<script>alert("删除成功");location.href="/myadmin/user/index/";</script>')


